<script setup lang="ts">
defineOptions({
  name: "add"
});

import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import {
  queryGasDeviceCode,
  createGasBottle,
  updateGasBottle,
  createGasReturnBottle,
  updateGasReturnBottle,
  createGasExpiredBottle,
  updateGasExpiredBottle,
  queryGasBottleDetail,
  getGasBottleOrderOptions
} from "@/api/modules/operation";
import { queryEquipSystem } from "@/api/equip/archive";
import { useRouterStoreHook } from "@/store/modules/router";
import dayjs from "dayjs";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

const routerStore = useRouterStoreHook();

interface Props {
  // 弹框类型 add 新增   edit 编辑
  type: "add" | "edit";
  // 生命周期(1:在库,2:返库,3:过期)
  lifeCycle: 1 | 2 | 3;
  id: string;
}

const props = withDefaults(defineProps<Props>(), {});
const dialogTableVisible = defineModel({ type: Boolean, default: false });
const title = computed(() => (props.type === "add" ? "新增" : "编辑"));
const gasNameOptions = ref<Array<any>>([]);
const deviceCodeLoading = ref(false);
const loading = ref(false);
const deviceCodeOptions = ref<Array<any>>([]);
const workOrderNoOptions = ref<Array<any>>([]);
const positionOptions = ["左", "右"];
const deviceCodeFlag = ref(false);
const positionFlag = ref(false);
const onlineOperatorFlag = ref(false);

const inertGasOptions = [
  {
    label: "是",
    value: "是"
  },
  {
    label: "否",
    value: "否"
  }
];

const unitOptions = [
  {
    label: "Psi",
    value: "Psi"
  },
  {
    label: "Lbs",
    value: "Lbs"
  }
];

interface RuleForm {
  cylinderNo: string;
  gasName: string;
  expirationDate: string;
  delayDate: string;
  materialNo: string;
  inertGas: string;
  returnWarehouse: string;
  applicationDate: string;
  costCenter: string;
  storesRequisitionNo: string;
  materialHandler: string;
  receiver: string;
  onlineDate: string;
  offlineDate: string;
  workOrderNo: string;
  deviceCode: string;
  position: string;
  onlineOperator: string;
  offlineOperator: string;
  unit: string;
  maximalCapacity: string;
  surplusCapacity: string;
  remark: string;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  cylinderNo: "",
  gasName: "",
  expirationDate: "",
  delayDate: "",
  materialNo: "",
  inertGas: "",
  returnWarehouse: "",
  applicationDate: "",
  costCenter: "",
  storesRequisitionNo: "",
  materialHandler: "",
  receiver: "",
  onlineDate: "",
  offlineDate: "",
  workOrderNo: "",
  deviceCode: "",
  position: "",
  onlineOperator: "",
  offlineOperator: "",
  unit: "Psi",
  maximalCapacity: "",
  surplusCapacity: "",
  remark: ""
});

const rules = reactive<FormRules<RuleForm>>({
  cylinderNo: [{ required: true, message: "请输入气瓶号", trigger: "blur" }],
  gasName: [{ required: true, message: "请输入气体名称", trigger: "blur" }],
  expirationDate: [{ required: true, message: "请选择有效期", trigger: "blur" }],
  delayDate: [{ required: false, message: "请选择延期至", trigger: "blur" }],
  materialNo: [{ required: true, message: "请输入料号", trigger: "blur" }],
  inertGas: [{ required: true, message: "请选择是否惰性", trigger: "blur" }],
  returnWarehouse: [{ required: false, message: "请选择是否返回", trigger: "blur" }],
  applicationDate: [{ required: false, message: "请选择申请日期", trigger: "blur" }],
  costCenter: [{ required: false, message: "请输入成本中心", trigger: "blur" }],
  storesRequisitionNo: [{ required: false, message: "请输入领料单号", trigger: "blur" }],
  materialHandler: [{ required: false, message: "请选择领料人", trigger: "blur" }],
  receiver: [{ required: false, message: "请选择接收人", trigger: "blur" }],
  onlineDate: [{ required: false, message: "请选择", trigger: "blur" }],
  offlineDate: [{ required: false, message: "请选择", trigger: "blur" }],
  workOrderNo: [{ required: false, message: "请选择更换工单号", trigger: "blur" }],
  deviceCode: [{ required: true, message: "请选择设备编号", trigger: "blur" }],
  position: [{ required: true, message: "请选择点位", trigger: "blur" }],
  onlineOperator: [{ required: false, message: "请输入上线操作人", trigger: "blur" }],
  offlineOperator: [{ required: false, message: "请输入下线操作人", trigger: "blur" }],
  unit: [{ required: false, message: "请输入单位", trigger: "blur" }],
  maximalCapacity: [{ required: false, message: "请输入满瓶量", trigger: "blur" }],
  surplusCapacity: [{ required: false, message: "请输入剩余量", trigger: "blur" }],
  remark: [{ required: false, message: "请输入备注", trigger: "blur" }]
});

const emits = defineEmits(["submit"]);

const delayDateDisabledDateFn = (d: Date) => {
  const timeStamp = new Date(d).getTime();
  if (ruleForm.expirationDate && timeStamp < dayjs(ruleForm.expirationDate).valueOf()) return true;
  return false;
};

const workOrderNoChangeHandler = (val: string) => {
  const item = workOrderNoOptions.value.find(item => item.value === val);
  const { deviceCode, position, executorName } = item;
  ruleForm.deviceCode = deviceCode;
  ruleForm.position = position;
  ruleForm.onlineOperator = executorName;
  deviceCodeFlag.value = !!deviceCode;
  positionFlag.value = !!position;
  onlineOperatorFlag.value = !!executorName;
};

const deviceCodeRemoteMethod = async (eqpId: string) => {
  deviceCodeOptions.value = [];
  if (eqpId) {
    deviceCodeLoading.value = true;
    const { subject: className } = routerStore;
    const categoryIds = [90, 94, 98, 88, 101];
    // facCode   一期  FAC_83abf9   二期  FAC_93abf6
    const facCode = localStorage.getItem("facCode");
    const systemCodes = facCode === "FAC_83abf9" ? ["SCA6CC96"] : facCode === "FAC_93abf6" ? ["SCC3F1B9"] : [];
    const params = { eqpId, className, systemCodes, categoryIds };
    const res = await queryGasDeviceCode(params);
    deviceCodeOptions.value = res.map(item => ({ ...item, label: item.eqpId, value: item.eqpId }));
    deviceCodeLoading.value = false;
  }
};

const cancelHandler = () => {
  dialogTableVisible.value = false;
};

const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const { lifeCycle, id } = props;
      const params = { ...ruleForm, lifeCycle };
      if (props.type === "add") {
        switch (props.lifeCycle) {
          case 1:
            await createGasBottle(params, () => {
              loading.value = false;
            });
            break;
          case 2:
            await createGasReturnBottle(params, () => {
              loading.value = false;
            });
            break;
          case 3:
            await createGasExpiredBottle(params, () => {
              loading.value = false;
            });
            break;
        }
      } else if (props.type === "edit") {
        params["id"] = id;
        switch (props.lifeCycle) {
          case 1:
            await updateGasBottle(params, () => {
              loading.value = false;
            });
            break;
          case 2:
            await updateGasReturnBottle(params, () => {
              loading.value = false;
            });
            break;
          case 3:
            await updateGasExpiredBottle(params, () => {
              loading.value = false;
            });
            break;
        }
      }
      loading.value = false;
      emits("submit");
      dialogTableVisible.value = false;
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);

const initGasNameOptions = async () => {
  gasNameOptions.value = [];
  const res: Array<any> = await queryEquipSystem({ className: "GAS" });
  // facCode   一期  FAC_83abf9   二期  FAC_93abf6
  const facCode = localStorage.getItem("facCode");
  const systemCode = facCode === "FAC_83abf9" ? "SCA6CC96" : facCode === "FAC_93abf6" ? "SCC3F1B9" : "";
  const t = res.find(item => item.code === systemCode);
  if (!t?.children?.length) return;
  gasNameOptions.value = t.children.map(item => {
    let { name } = item;
    const reg = new RegExp("供应系统", "g");
    name = name.replace(reg, "");
    return { label: name, value: name };
  });
};

const initWorkOrderNoOptions = async () => {
  workOrderNoOptions.value = [];
  const res: Array<any> = await getGasBottleOrderOptions({ taskNo: "" }, () => {
    loading.value = false;
  });
  if (!res?.length) return;
  workOrderNoOptions.value = res.map(item => {
    const { workOrderNo } = item;
    item["value"] = workOrderNo;
    item["label"] = workOrderNo;
    return item;
  });
};

const init = async () => {
  loading.value = true;
  await initGasNameOptions();
  await initWorkOrderNoOptions();
  if (props.type === "edit") {
    const { id } = props;
    const res = await queryGasBottleDetail(id, () => {
      loading.value = false;
    });
    const {
      cylinderNo = "",
      gasName = "",
      expirationDate = "",
      delayDate = "",
      materialNo = "",
      inertGas = "",
      returnWarehouse = "",
      applicationDate = "",
      costCenter = "",
      storesRequisitionNo = "",
      materialHandler = "",
      receiver = "",
      onlineDate = "",
      offlineDate = "",
      workOrderNo = "",
      deviceCode = "",
      position = "",
      onlineOperator = "",
      offlineOperator = "",
      unit = "",
      maximalCapacity = "",
      surplusCapacity = "",
      remark = ""
    } = res;
    ruleForm.cylinderNo = cylinderNo;
    ruleForm.gasName = gasName;
    ruleForm.expirationDate = expirationDate;
    ruleForm.delayDate = delayDate;
    ruleForm.materialNo = materialNo;
    ruleForm.inertGas = inertGas;
    ruleForm.returnWarehouse = returnWarehouse;
    ruleForm.applicationDate = applicationDate;
    ruleForm.costCenter = costCenter;
    ruleForm.storesRequisitionNo = storesRequisitionNo;
    ruleForm.materialHandler = materialHandler;
    ruleForm.receiver = receiver;
    ruleForm.onlineDate = onlineDate;
    ruleForm.offlineDate = offlineDate;
    ruleForm.workOrderNo = workOrderNo;
    deviceCodeOptions.value = [{ label: deviceCode, value: deviceCode }];
    ruleForm.deviceCode = deviceCode;
    ruleForm.position = position;
    ruleForm.onlineOperator = onlineOperator;
    ruleForm.offlineOperator = offlineOperator;
    ruleForm.unit = unit;
    ruleForm.maximalCapacity = maximalCapacity;
    ruleForm.surplusCapacity = surplusCapacity;
    ruleForm.remark = remark;
  }
  loading.value = false;
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <px-dialog v-model="dialogTableVisible" :title="title" width="1000px">
    <px-form
      ref="ruleFormRef"
      v-loading="loading"
      :model="ruleForm"
      :rules="rules"
      inline
      label-width="100px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <px-row :gutter="32">
        <px-col :span="12">
          <px-form-item label="气瓶号" prop="cylinderNo">
            <px-input v-model.trim="ruleForm.cylinderNo" clearable placeholder="请输入气瓶号" />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="气体名称" prop="gasName">
            <px-select v-model="ruleForm.gasName" clearable filterable placeholder="请选择气体名称">
              <px-option v-for="item in gasNameOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="有效期" prop="expirationDate">
            <px-date-picker
              v-model="ruleForm.expirationDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              placeholder="请选择有效期"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="延期至" prop="delayDate">
            <px-date-picker
              v-model="ruleForm.delayDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              :disabled-date="delayDateDisabledDateFn"
              placeholder="请选择延期至"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="料号" prop="materialNo">
            <px-input v-model.trim="ruleForm.materialNo" clearable placeholder="请输入料号" />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="是否惰性" prop="inertGas">
            <px-select v-model="ruleForm.inertGas" clearable filterable placeholder="请选择是否惰性">
              <px-option v-for="item in inertGasOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="申请日期" prop="applicationDate">
            <px-date-picker
              v-model="ruleForm.applicationDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              placeholder="请选择申请日期"
            />
          </px-form-item>
        </px-col>
        <px-col v-if="lifeCycle === 1" :span="12">
          <px-form-item label="成本中心" prop="costCenter">
            <px-input v-model.trim="ruleForm.costCenter" clearable placeholder="请输入成本中心" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="领料单号" prop="storesRequisitionNo">
            <px-input v-model.trim="ruleForm.storesRequisitionNo" clearable placeholder="请输入领料单号" />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="领料人" prop="materialHandler">
            <px-input v-model.trim="ruleForm.materialHandler" clearable placeholder="请输入领料人" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="接收人" prop="receiver">
            <px-input v-model.trim="ruleForm.receiver" clearable placeholder="请输入接收人" />
          </px-form-item>
        </px-col>
        <px-col v-if="lifeCycle === 1" :span="12">
          <px-form-item label="换瓶日期" prop="onlineDate">
            <px-date-picker
              v-model="ruleForm.onlineDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              placeholder="请选择换瓶日期"
            />
          </px-form-item>
        </px-col>

        <px-col v-if="lifeCycle === 2 || lifeCycle === 3" :span="12">
          <px-form-item label="上线日期" prop="onlineDate">
            <px-date-picker
              v-model="ruleForm.onlineDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              placeholder="请选择上线日期"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="更换工单号" prop="workOrderNo" :required="lifeCycle === 1">
            <px-select
              v-model="ruleForm.workOrderNo"
              clearable
              filterable
              reserve-keyword
              placeholder="请选择更换工单号"
              @change="workOrderNoChangeHandler"
            >
              <px-option v-for="item in workOrderNoOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="设备编号" prop="deviceCode">
            <px-select
              v-model="ruleForm.deviceCode"
              :disabled="!!ruleForm.workOrderNo && !!ruleForm.deviceCode && deviceCodeFlag"
              clearable
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              placeholder="请输入设备编号搜索"
              :remote-method="deviceCodeRemoteMethod"
              :loading="deviceCodeLoading"
            >
              <px-option v-for="item in deviceCodeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="点位" prop="position">
            <px-select
              v-model="ruleForm.position"
              :disabled="!!ruleForm.workOrderNo && !!ruleForm.position && positionFlag"
              clearable
              filterable
              placeholder="请选择点位"
            >
              <px-option v-for="item in positionOptions" :key="item" :label="item" :value="item" />
            </px-select>
          </px-form-item>
        </px-col>

        <px-col v-if="lifeCycle === 1" :span="12">
          <px-form-item label="更换人" prop="onlineOperator">
            <px-input
              v-model.trim="ruleForm.onlineOperator"
              :disabled="!!ruleForm.workOrderNo && !!ruleForm.onlineOperator && onlineOperatorFlag"
              clearable
              placeholder="请输入更换人"
            />
          </px-form-item>
        </px-col>

        <px-col v-if="lifeCycle === 2 || lifeCycle === 3" :span="12">
          <px-form-item label="上线操作人" prop="onlineOperator">
            <px-input v-model.trim="ruleForm.onlineOperator" clearable placeholder="请输入上线操作人" />
          </px-form-item>
        </px-col>

        <px-col v-if="lifeCycle === 2 || lifeCycle === 3" :span="12">
          <px-form-item label="下线日期" prop="offlineDate">
            <px-date-picker
              v-model="ruleForm.offlineDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              placeholder="请选择下线日期"
            />
          </px-form-item>
        </px-col>

        <px-col v-if="lifeCycle === 2" :span="12">
          <px-form-item label="是否返回" prop="returnWarehouse">
            <px-select v-model="ruleForm.returnWarehouse" clearable filterable placeholder="请选择是否返回">
              <px-option v-for="item in inertGasOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>

        <px-col v-if="lifeCycle === 2 || lifeCycle === 3" :span="12">
          <px-form-item label="下线操作人" prop="offlineOperator">
            <px-input v-model.trim="ruleForm.offlineOperator" clearable placeholder="请输入下线操作人" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="满瓶量" prop="maximalCapacity">
            <px-input v-model.trim="ruleForm.maximalCapacity" clearable placeholder="请输入满瓶量">
              <template #append>
                <px-select v-model="ruleForm.unit" filterable style="width: 96px">
                  <px-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value" />
                </px-select>
              </template>
            </px-input>
          </px-form-item>
        </px-col>

        <px-col v-if="lifeCycle === 3" :span="12">
          <px-form-item label="剩余量" prop="surplusCapacity">
            <px-input v-model.trim="ruleForm.surplusCapacity" clearable placeholder="请输入剩余量">
              <template #append>
                <px-select v-model="ruleForm.unit" filterable style="width: 96px">
                  <px-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value" />
                </px-select>
              </template>
            </px-input>
          </px-form-item>
        </px-col>

        <px-col :span="24">
          <px-form-item label="备注" prop="remark">
            <px-input v-model.trim="ruleForm.remark" clearable type="textarea" maxlength="200" show-word-limit placeholder="请输入备注" />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>

    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;

  .px-form-item__content {
    .px-input,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}
</style>
